package es.aa.android.cartomatic.customview;


import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;

/**
 * Created by Arturo on 27/08/2014.
 */
public class mListView extends GridView {

    private boolean expanded = true;
    private int numColumnsPotrait = 0;
    private int numColumnsLandScape = 0;

    public mListView(Context context) {
        super(context);
        init(context);
    }

    public mListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public mListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public boolean isExpanded() {
        return expanded;
    }

    public void setExpanded(boolean expanded) {
        this.expanded = expanded;
    }

    private void init(final Context context) {

    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (isExpanded()) {
            int expandSpec = MeasureSpec.makeMeasureSpec(
                    Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);

            ViewGroup.LayoutParams params = getLayoutParams();
            params.height = getMeasuredHeight();
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public void setNumColumns(int numColumnsPotrait, int numColumnsLandScape) {
        this.numColumnsPotrait = numColumnsPotrait;
        this.numColumnsLandScape = numColumnsLandScape;
        onConfigurationChanged(getResources().getConfiguration());
    }

    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT && numColumnsPotrait != 0) {
            setNumColumns(numColumnsPotrait);
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE && numColumnsLandScape != 0) {
            setNumColumns(numColumnsLandScape);
        }
        super.onConfigurationChanged(newConfig);
    }

}
